package com.john.blog.common.utils;

import javax.servlet.http.HttpServletRequest;

import com.john.blog.common.constant.KeyConst;
import com.john.blog.common.vo.UrlPoint;

/**
 * 请求工具
 * 
 * @author JiangGengchao
 * @date 2018年2月9日
 */
public abstract class RequestUtils {

    public static String getBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }

    public static UrlPoint getUrlEndPoint(HttpServletRequest request) {
        UrlPoint endPoint = new UrlPoint();
        endPoint.setName((request.getLocalName() != null) ? request.getLocalName() : null);
        endPoint.setAddress((request.getLocalAddr() != null) ? request.getLocalAddr() : null);
        endPoint.setPort(request.getLocalPort());
        endPoint.setContext(request.getServletPath());
        return endPoint;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static boolean isPublicResourceRequest(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        String lowerCaseServletPath = servletPath.toLowerCase();
        return lowerCaseServletPath.endsWith(".js") || lowerCaseServletPath.endsWith(".css") || lowerCaseServletPath.endsWith(".jpg") //
                || lowerCaseServletPath.endsWith(".gif") || lowerCaseServletPath.endsWith(".bmp") || lowerCaseServletPath.endsWith(".png") || lowerCaseServletPath.endsWith(".ico");
    }

    public static Integer getPageSize(HttpServletRequest request) {
        Integer pageSize = (Integer) request.getAttribute(KeyConst.PAGE_SIZE);
        if (pageSize == null) {
            pageSize = KeyConst.DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }

    public static Integer getPageNum(HttpServletRequest request) {
        Integer pageNum = (Integer) request.getAttribute(KeyConst.PAGE_NUM);
        if (pageNum == null) {
            pageNum = 1;
        }
        return pageNum;
    }

    public static Boolean toBoolean(String value) {
        if (DetectUtils.isEmpty(value))
            return Boolean.FALSE;
        value = value.trim().toLowerCase();
        if ("1".equals(value) || "true".equals(value)) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

}
